import React, { useEffect, useState } from 'react';
import {
  message,
  Radio,
  Select,
  Checkbox,
  Table,
  Tag,
  Space,
  Form,
  Input,
  Button,
  Cascader,
  DatePicker,
  Drawer,
  Modal,
  Descriptions,
} from 'antd';
import { SettingFilled, EyeOutlined } from '@ant-design/icons';
import {
  addUserAPI,
  getDeptsAPI,
  getUsersAPI,
  modiUserAPI,
} from '../../../apis/user/userAPI';
import styles from '@/assets/css/User.less';
import { getCharactersAPI } from '../../../apis/character/character';
const { RangePicker } = DatePicker;
const { Option } = Select;

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

export default function User() {
  const getUsers = async (params) => {
    const res = await getUsersAPI({ ...params, ...pageInfo, ...searchInfo });
    console.log('getUsers', res);
    setUsersData(res.data.rows);
    setPageInfo({ ...pageInfo, total: res.data.rows.length });
  };

  const getDepts = async () => {
    const res = await getDeptsAPI();
    console.log('getDepts', res);
    setDeptsData(res.data.rows.children);
  };
  const getRoles = async () => {
    const res = await getCharactersAPI();
    console.log('getRoles', res);
    setRolesData(res.data.rows);
  };
  const pagChange = async (pageNum, pageSize) => {
    setPageInfo({ ...pageInfo, pageNum, pageSize });
    getUsers();
  };
  const casChange = (value) => {
    // console.log(value);
    setSearchInfo({ ...searchInfo, deptId: value[value.length - 1] });
  };
  const addCasChange = (value) => {
    // console.log(value);
    setAddUserObj({ ...addUserObj, deptId: value[value.length - 1] });
  };

  const searchFunc = async (values) => {
    // console.log('Success:', values);
    const { username } = values;
    setSearchInfo({ ...searchInfo, username });
    await getUsers();
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const addUser = async (values) => {
    console.log(values);
    values.roleId = values.roleId.join(',');
    const res = await addUserAPI({ ...values, ...addUserObj });
    console.log('addUser', res);
    if (res.status == 200) {
      setAddDrawer(false);
      message.success('新增成功');
    }

    await getUsers();
  };
  const showModi = (user) => {
    console.log(user);
    setTimeout(() => {
      setModiDrawer(true);
      let { roleId } = user;
      if (roleId) {
        roleId = user.roleId.split(',');
      }
      modiForm.setFieldsValue({ ...user, roleId });
      // const arr = createDeptArr(deptsData, user.deptId)
      // setModiUser({ ...user });
    }, 0);
  };
  const modiUserAsync = async (user) => {
    let { roleId, deptId } = user;
    user.roleId = roleId.join(',');
    const res = await modiUserAPI(user);
    console.log('modiUser', res);
  };
  const showUserDetails = (user) => {
    setDetailUser(user);
  };
  const detailClose = () => {
    setDetailUser(null);
  };
  const createDeptArr = (arr, id) => {
    for (let i = 0; i < arr.length; i++) {
      const dp = arr[i];
      if (dp.id == id) {
        return [id];
      } else {
        if (dp.children) {
          const childReturn = createDeptArr(dp.children, id);
          const insert = childReturn == undefined ? [undefined] : [childReturn];
          let res = [dp.id, ...insert];
          if (!res.includes(undefined)) {
            console.log(res);
            return res;
          }
        }
      }
    }
  };

  //state部分
  const [modiForm] = Form.useForm();
  const [usersData, setUsersData] = useState([]);
  let [pageInfo, setPageInfo] = useState({ pageNum: 1, pageSize: 1, total: 0 });
  let [searchInfo, setSearchInfo] = useState({});
  let [deptsData, setDeptsData] = useState([]);
  let [rolesData, setRolesData] = useState([]);
  let [addDrawer, setAddDrawer] = useState(false);
  let [addUserObj, setAddUserObj] = useState({});
  let [modiDrawer, setModiDrawer] = useState(false);
  let [modiUser, setModiUser] = useState({});
  let [detailUser, setDetailUser] = useState(null);
  let [chooseUsers, setChooseUsers] = useState([]);
  //effect部分
  // 挂载后
  useEffect(() => {
    getUsers();
    getDepts();
    getRoles();
  }, []);
  let pagination = {
    total: pageInfo.total,
    showTotal: (total, range) => `${range[0]}-${range[1]} 条，共 ${total} 条`,
    showSizeChanger: true,
    pageSizeOptions: [1, 2, 3, 4, 5],
    defaultPageSize: 3,
    defaultCurrent: 1,
    onchange: pagChange,
  };
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      key: 'ssex',
      render: (ssex) => {
        let text;
        if (ssex == '0') {
          text = '男';
        } else if (ssex == '1') {
          text = '女';
        } else if (ssex == '2') {
          text = '保密';
        }
        return text;
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (status) => {
        const flag = status == '1';
        const text = flag ? '有效' : '锁定';
        const color = flag ? 'success' : 'error';

        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'userId',
      render: (data) => (
        <Space size="middle">
          <SettingFilled
            style={{ color: '#5eaaf6' }}
            onClick={() => showModi(data)}
          ></SettingFilled>
          <EyeOutlined
            style={{ color: '#5ac293' }}
            onClick={() => showUserDetails(data)}
          >
            {' '}
          </EyeOutlined>
        </Space>
      ),
    },
  ];
  const rowSec = {
    type: 'checkbox',
  };
  return (
    <div style={{ width: '100%' }}>
      用户管理
      <div className={styles.userHead}>
        {/* 搜索栏 */}
        <Form
          name="basic"
          {...layout}
          layout="inline"
          onFinish={searchFunc}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="用户名" name="username">
            <Input />
          </Form.Item>

          <Form.Item label="部门" name="deptId">
            <Cascader
              fieldNames={{ label: 'text', value: 'id' }}
              options={deptsData}
              onChange={casChange}
              placeholder="Please select"
            />
          </Form.Item>
          <Form.Item label="创建日期" name="createTime">
            <RangePicker
              onChange={(_, dates) => {
                const [createTimeFrom, createTimeTo] = dates;
                setSearchInfo({ ...searchInfo, createTimeFrom, createTimeTo });
              }}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className={styles.opers}>
        <Button type="primary" onClick={() => setAddDrawer(!addDrawer)}>
          新增
        </Button>
      </div>
      <Table
        pagination={pagination}
        dataSource={usersData}
        columns={columns}
        rowSelection={rowSec}
        className={styles.userTable}
      />
      {/* 新增用户抽屉 */}
      <Drawer
        destroyOnClose
        width={482}
        title="新增用户"
        placement="right"
        onClose={() => setAddDrawer(false)}
        visible={addDrawer}
      >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={addUser}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="部门" name="deptId">
            <Cascader
              fieldNames={{ label: 'text', value: 'id' }}
              options={deptsData}
              onChange={addCasChange}
              placeholder="Please select"
            />
          </Form.Item>
          <Form.Item
            label="角色"
            name="roleId"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Select mode="multiple">
              {rolesData.map((r) => (
                <Option key={r.roleId}>{r.roleName}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="ssex"
            label="性别"
            wrapperCol={{ offset: 8, span: 16 }}
          >
            <Radio.Group>
              <Radio value="0">男</Radio>
              <Radio value="1">女</Radio>
              <Radio value="2">保密</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            wrapperCol={{ offset: 8, span: 16 }}
          >
            <Radio.Group>
              <Radio value="1">有效</Radio>
              <Radio value="0">锁定</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              新增
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
      {/* 修改用户抽屉 */}
      <Drawer
        destroyOnClose
        width={482}
        title="修改用户"
        placement="right"
        onClose={() => setModiDrawer(false)}
        visible={modiDrawer}
      >
        {modiDrawer ? (
          <Form
            form={modiForm}
            name="basic"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            onFinish={(values) => modiUserAsync(values)}
            autoComplete="off"
            defaultValue={modiUser}
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
              rules={[
                { required: true, message: 'Please input your password!' },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item label="部门" name="deptId">
              {modiUser.deptId instanceof Array ? (
                <Cascader
                  fieldNames={{ label: 'text', value: 'id' }}
                  options={deptsData}
                  defaultValue={modiUser.deptId}
                  placeholder="选择要修改的部门"
                />
              ) : null}
            </Form.Item>
            <Form.Item
              label="角色"
              name="roleId"
              rules={[
                { required: true, message: 'Please input your username!' },
              ]}
            >
              <Select mode="multiple">
                {rolesData.map((r) => (
                  <Option key={r.roleId}>{r.roleName}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="ssex"
              label="性别"
              wrapperCol={{ offset: 8, span: 16 }}
            >
              <Radio.Group>
                <Radio value="0">男</Radio>
                <Radio value="1">女</Radio>
                <Radio value="2">保密</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="status"
              label="状态"
              wrapperCol={{ offset: 8, span: 16 }}
            >
              <Radio.Group>
                <Radio value="1">有效</Radio>
                <Radio value="0">锁定</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                修改
              </Button>
            </Form.Item>
          </Form>
        ) : null}
      </Drawer>
      {/* 详情模态框 */}
      <Modal
        title="用户信息"
        visible={detailUser}
        onOk={detailClose}
        onCancel={detailClose}
      >
        <Descriptions title="User Info" layout="vertical">
          {(function () {
            const arr = [];
            for (const key in detailUser) {
              arr.push(
                <Descriptions.Item label={key}>
                  {detailUser[key]}
                </Descriptions.Item>,
              );
            }
            return arr;
          })()}
        </Descriptions>
      </Modal>
    </div>
  );
}
